package org.linlinjava.litemall.db.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class BeanUtil {

    /**
     * 单个对象拷贝
     *
     * @param source 源对象
     * @param targetClass 目标类
     * @param <T> 目标类型
     * @return 目标对象
     */
    public static <T> T copy(Object source, Class<T> targetClass) {
        if (source == null) {
            return null;
        }
        try {
            T target = targetClass.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(source, target);
            return target;
        } catch (Exception e) {
            throw new RuntimeException("Bean copy error", e);
        }
    }

    /**
     * 集合拷贝
     *
     * @param sourceList 源集合
     * @param targetClass 目标类
     * @param <T> 目标类型
     * @return 目标集合
     */
    public static <T> List<T> copyList(List<?> sourceList, Class<T> targetClass) {
        List<T> targetList = new ArrayList<>();
        if (sourceList == null || sourceList.isEmpty()) {
            return targetList;
        }
        for (Object source : sourceList) {
            targetList.add(copy(source, targetClass));
        }
        return targetList;
    }

    /**
     * 深拷贝 (通过序列化实现，可选)
     * 需要目标对象实现 Serializable
     */
    // public static <T extends Serializable> T deepCopy(T object) {
    //     try {
    //         ByteArrayOutputStream bos = new ByteArrayOutputStream();
    //         ObjectOutputStream oos = new ObjectOutputStream(bos);
    //         oos.writeObject(object);
    //         oos.flush();
    //         oos.close();
    //
    //         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    //         ObjectInputStream ois = new ObjectInputStream(bis);
    //         return (T) ois.readObject();
    //     } catch (IOException | ClassNotFoundException e) {
    //         throw new RuntimeException("Deep copy error", e);
    //     }
    // }
    /**
     * 分页对象拷贝
     *
     * @param sourcePage 源分页对象
     * @param targetClass 目标类
     * @param <S> 源对象类型
     * @param <T> 目标对象类型
     * @return 转换后的分页对象
     */
    public static <S, T> Page<T> copyPage(IPage<S> sourcePage, Class<T> targetClass) {
        Page<T> targetPage = new Page<>();
        targetPage.setCurrent(sourcePage.getCurrent());
        targetPage.setSize(sourcePage.getSize());
        targetPage.setTotal(sourcePage.getTotal());
        targetPage.setPages(sourcePage.getPages());
        targetPage.setRecords(copyList(sourcePage.getRecords(), targetClass));
        return targetPage;
    }
}
